import { createRouter, createWebHistory } from "vue-router";

// 创建路由组
const routes = [
    {
        path: '/', component:()=>import('@/layouts/LayOut.vue'),redirect:'/home',
        children:[
            { name: 'home', path: 'home', component: () => import('@/pages/Home.vue') },
            { name: 'top', path: 'top', component: () => import('@/pages/Top.vue') },
            { name: 'search', path: 'search', component: () => import('@/pages/Search.vue') },
            { name: 'apiDetail', path: 'apiDetail', component: () => import('@/pages/ApiDetail.vue') },
            { name: 'upload', path: 'upload', component: () => import('@/pages/Upload.vue') },
          ]
    },
    { name: 'login', path: '/login', component: () => import('@/pages/Login.vue') },
    { name: 'register', path: '/register', component: () => import('@/pages/Register.vue') },
]
// 创建路由器
const router = createRouter({
    // 路由工作模式
    history: createWebHistory(),
    routes,
})

// 配置路由守卫
router.beforeEach(async (to, from) => {
    const isLogin = localStorage.getItem('userInfo')
    if (
      // 检查用户是否已登录
      !isLogin &&
      // ❗️ 避免无限重定向 以及过滤公共部分
      !['login','home','search','top','register'].includes(to.name as string)
    ) {
      ElMessage.warning('请先登录！')
      // 将用户重定向到登录页面
      return { name: 'login' }
    }
  })

export default router